package feeds;

import html.HTMLElem;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.JSONHelpers;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import ajaxmethods.AjaxMethod;
import ajaxmethods.SessionMethod;

public class Feedzilla extends SessionMethod  {



	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		super.perform(request, response);
		response.setContentType("text/json");
		StringBuilder sb = new StringBuilder();
		Integer page = (Integer)request.getSession().getAttribute("page");
		JSONArray articles = (JSONArray)request.getSession().getAttribute("articles");

		if(page==null)
		{
			page=0;
		}
		if(request.getParameter("next")!=null)
		{
			page++;
			if(page>= articles.length())
				page=0;
		}
		if(request.getParameter("prev")!=null)
		{
			page--;
			if(page<0)
				page=articles.length()-1;
		}
		
		request.getSession().setAttribute("page", page);
		
		if(articles==null)
		{
			articles = getCategories(page);
			request.getSession().setAttribute("articles", articles);
		}
		
		try {
			data.put("article",articles.get(page)).write(response.getWriter());
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private org.json.JSONArray getCategories(Integer page) {
		try {
			
			URL categoriesURL = new URL("http://api.feedzilla.com/v1/categories/22/subcategories/1160/articles.json");
			//URL categoriesURL = new URL("http://www.austinrealestateguy.com/blogs/MainFeed.aspx");
			URLConnection connect = categoriesURL.openConnection();
			InputStream is = connect.getInputStream();
			final char[] buffer = new char[0x10000];
			StringBuilder out = new StringBuilder();
			Reader in = new InputStreamReader(is, "UTF-8");
			int read;
			do {
			  read = in.read(buffer, 0, buffer.length);
			  if (read>0) {
			    out.append(buffer, 0, read);
			  }
			} while (read>=0);
			
		        in.close();
		        JSONObject o = new JSONObject(out.toString());
		       return o.getJSONArray("articles");
		   
		        
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}

	
	
}
